import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop_z/model/category_sub.dart';
import 'package:flutter_shop_z/model/commodity.dart';
import 'package:flutter_shop_z/pages/category_page/bloc/category_sub_bloc.dart';
import 'package:flutter_shop_z/pages/details_page.dart';
import 'package:flutter_shop_z/service/service_method.dart';
import 'package:flutter_shop_z/config/service_url.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';

class BottomCommodity extends StatefulWidget {
  @override
  _BottomCommodity createState() => _BottomCommodity();
}

class _BottomCommodity extends State<BottomCommodity> {
  int categoryId = 0;
  int categorySubId = 0;
  List<Commodity> commodityList = [];
  int pageNum = 1;

  @override
  void initState() {
    _categorySubCommodityList(false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CategorySubBloc, CategorySubState>(
        builder: (context, state) {
      if (state.categorySub == null) {
        return Text('数据加载中');
      } else {
        CategorySub categorySub = state.categorySub;
        if (categoryId != categorySub.categoryId ||
            categorySubId != categorySub.categorySubId) {
          categoryId = categorySub.categoryId;
          categorySubId = categorySub.categorySubId;
          _categorySubCommodityList(false);
        }
        return Container(
            height: ScreenUtil().setHeight(971),
            width: ScreenUtil().setWidth(570),
            child: commodityList.length == 0
                ? Center(
                    child: Text(
                    '暂时没有商品',
                    style: TextStyle(color: Colors.red),
                  ))
                : EasyRefresh(
                    child: ListView.builder(
                      itemBuilder: (context, index) {
                        return _commodityItem(commodityList[index], index);
                      },
                      itemCount: commodityList.length,
                    ),
                    onLoad: () {
                      _categorySubCommodityList(true);
                    },
                    onRefresh: () {
                      _categorySubCommodityList(false);
                    },
                  ));
      }
    });
  }

  void _categorySubCommodityList(bool onLoad) async {
    if (categoryId != 0 && categorySubId != 0) {
      var formData = {
        'categoryId': categoryId,
        'categorySubId': categorySubId,
        'pageNum': onLoad ? pageNum : 1
      };
      await getRequest(servicePath['categorySubCommodityList'], formData)
          .then((value) {
        List<Map> list = (value['data'] as List).cast();
        if (!onLoad) {
          commodityList.clear();
          setState(() {
            commodityList = list.map((e) => Commodity.fromJson(e)).toList();
            pageNum = 2;
          });
        } else {
          setState(() {
            ++pageNum;
            if (list.map((e) => Commodity.fromJson(e)).toList() == null) {
              Fluttertoast.showToast(msg: '数据加载完毕');
            } else {
              commodityList
                  .addAll(list.map((e) => Commodity.fromJson(e)).toList());
            }
          });
        }
      });
    }
  }

  Widget _commodityImage(Commodity commodity) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(
          '${serviceUrl}goods/${commodity.categoryId}/${commodity.categorySubId}/${commodity.commodityImg}'),
    );
  }

  Widget _commodityName(Commodity commodity) {
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        commodity.commodityName == null ? "" : commodity.commodityName,
        overflow: TextOverflow.ellipsis,
        maxLines: 2,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  Widget _commodityPrice(Commodity commodity) {
    return Container(
      margin: EdgeInsets.only(top: 20),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text(
            '价格:￥${commodity.commodityDiscountPrice}',
            style: TextStyle(
              color: Colors.purple,
              fontSize: ScreenUtil().setSp(30),
            ),
          ),
          Container(
            width: 10,
          ),
          Text(
            '￥${commodity.commodityOriginalPrice}',
            style: TextStyle(
              color: Colors.black26,
              decoration: TextDecoration.lineThrough,
            ),
          ),
        ],
      ),
    );
  }

  Widget _commodityItem(Commodity commodity, index) {
    return InkWell(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return DetailsPage(commodity.commodityId);
        }));
      },
      child: Container(
        height: ScreenUtil().setHeight(250),
        padding: EdgeInsets.only(top: 5, bottom: 5),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(width: 1, color: Colors.black12),
          ),
        ),
        child: Row(
          children: <Widget>[
            _commodityImage(commodity),
            Column(
              children: <Widget>[
                _commodityName(commodity),
                _commodityPrice(commodity),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
